package com.cskaoyan.service;

import com.cskaoyan.annotation.ExecutionLog;
import com.cskaoyan.bean.bo.WxglMallManagementControllerBo.IssueCreateBo;
import com.cskaoyan.bean.bo.WxglMallManagementControllerBo.KeywordListBo;
import com.cskaoyan.bean.bo.WxglMallManagementControllerBo.OrderListBo;
import com.cskaoyan.bean.bo.WxglMallManagementControllerBo.PostPermissionBo;
import com.cskaoyan.bean.common.BasePageInfo;
import com.cskaoyan.bean.common.CommonData;
import com.cskaoyan.bean.common.Constant;
import com.cskaoyan.bean.marketBean.*;
import com.cskaoyan.bean.vo.WxglMallManagementControllerVo.*;
import com.cskaoyan.mapper.marketMapper.MarketIssueMapper;
import com.cskaoyan.mapper.marketMapper.MarketKeywordMapper;
import com.cskaoyan.mapper.marketMapper.MarketOrderMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;

import javax.validation.Valid;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author wxgl
 * @date 2022-12-29 10:46
 * @describe
 */
@Service
@Transactional
public class WxglMarketManagementServiceImpl implements WxglMarketManagementService{

    @Autowired
    MarketOrderMapper orderMapper;
    @Autowired
    MarketIssueMapper marketIssueMapper;
    @Autowired
    MarketKeywordMapper marketKeywordMapper;

    /**
     * @Author xiaowu
     * @Description //TODO http://localhost:8083/admin/order/list?page=1&limit=20&sort=add_time&order=desc&start=&end=
     *           按照条件查询所有的订单信息
     * @Date 21:38 2022/12/28
     * @Param [info, start, end]
     * @return com.cskaoyan.bean.common.CommonData<com.cskaoyan.bean.vo.WxglMallManagementControllerVo.OrderListVo>
     **/
    @Override
    public CommonData<OrderListVo> orderList(OrderListBo bo) {
        //开始分页
        PageHelper.startPage(bo.getPage(),bo.getLimit());
        MarketOrderExample example = new MarketOrderExample();
        example.setDistinct(true);
        example.setOrderByClause(bo.getSort()+" "+bo.getOrder());

        MarketOrderExample.Criteria criteria = example.createCriteria();
        if ( bo.getOrderStatusArray()!= null && !"".equals(bo.getOrderStatusArray())) {//StringUtils isEmpty
            criteria.andOrderStatusEqualTo(bo.getOrderStatusArray());
        }
        if (bo.getOrderId() != null && !"".equals(bo.getOrderId())) {

            criteria.andIdEqualTo(bo.getOrderId());
        }
        if (bo.getStart() != null && !"".equals(bo.getStart())) {

            criteria.andUpdateTimeGreaterThanOrEqualTo(bo.getStart());
        }
        if (bo.getEnd() != null && !"".equals(bo.getEnd())) {

            criteria.andUpdateTimeLessThanOrEqualTo(bo.getEnd());
        }
        if (bo.getUserId() != null && !"".equals(bo.getUserId())) {

            criteria.andUserIdEqualTo(bo.getUserId());
        }
        if (bo.getOrderSn() != null && !"".equals(bo.getOrderSn())) {

            criteria.andOrderSnLike("%"+bo.getOrderSn()+"%");
        }
        if (1==1){
            criteria.andDeletedEqualTo(false);
        }
        List<OrderListVo> list = orderMapper.selectOrderListByExample(example);
        PageInfo<OrderListVo> pageInfo = new PageInfo<>(list);
        return CommonData.data(pageInfo);
    }

    /**
     * @Author xiaowu
     * @Description //TODO 获取所有的快递公司信息
     * @Date 22:19 2022/12/28
     * @Param []
     * @return java.util.List<com.cskaoyan.bean.marketBean.MarketChannel>
     **/
    @Override
    public List<MarketChannel> orderChannel() {
        List<MarketChannel> list = orderMapper.orderChannel();
        return list;
    }
    /**
     * @Author xiaowu
     * @Description //TODO 通过order的id查询order表、user表、orderGoods表
     * @Date 23:35 2022/12/28
     * @Param [id]
     * @return com.cskaoyan.bean.vo.WxglMallManagementControllerVo.OrderDetailVo
     **/
    @Override
    public OrderDetailVo orderDetail(Integer id) {
        OrderDetailVo orderDetailVo = new OrderDetailVo();

        OrderEntityVo order = orderMapper.selectOrderInfo(id);
        List<OrderGoodsEntityVo> orderGoods = orderMapper.selectOrderGoodsInfo(id);
        int userId = order.getUserId();
        UserEntityVo user = orderMapper.selectUserInfo(userId);

        orderDetailVo.setOrder(order);
        orderDetailVo.setOrderGoods(orderGoods);
        orderDetailVo.setUser(user);

        return orderDetailVo;
    }

    /**
     * @Author xiaowu
     * @Description //TODO 发货操作：即将指定的订单的状态改为已发货
     * @Date 0:20 2022/12/29
     * @Param [map]
     * @return void
     **/
    @Override
    public int orderShip(Map map) {
        Integer orderId = (Integer) map.get("orderId");
        String shipChannel = (String) map.get("shipChannel");
        String shipSn = (String) map.get("shipSn");
        Date date = new Date();
        
        int affectedRows = orderMapper.orderShip(orderId,shipChannel,shipSn,date);


        if (affectedRows == 0){
            return 10000;
        }
        return 200;
    }

    /**
     * @Author xiaowu
     * @Description //TODO 删除订单操作
     * @Date 0:50 2022/12/29
     * @Param [orderId]
     * @return int 订单状态为用户收货才可以返回200
     * 否则返回10000
     **/
    @Override
    public int orderDelete(Integer orderId) {

        int orderStatus = orderMapper.selectOrderStatusById(orderId);
        if (orderStatus == Constant.USER_GET_PACKAGE_CODE || orderStatus == Constant.SYSTEM_GET_PACKAGE_CODE|| orderStatus == Constant.REFUNDED_CODE){
            orderMapper.orderDelete(orderId);
            orderMapper.orderGoodsDelete(orderId);
            return 200;
        }
        return 10000;
    }

    /**
     * @Author xiaowu
     * @Description //TODO 退款
     * @Date 14:06 2022/12/29
     * @Param [map]  {"orderId":308,"refundMoney":383}
     * @return void
     **/
    @Override
    public void orderRefund(Map map) {
        Integer orderId = (Integer) map.get("orderId");
        Integer refundMoney = (Integer) map.get("refundMoney");

        String orderStatus = "203";
        String afterSaleStatus = "3";
        String refundType = "微信接口退款";
        String refundContent = "客户对产品质量不满";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String date = sdf.format(new Date());

        orderMapper.orderRefund(orderId,refundMoney,orderStatus,afterSaleStatus,refundType,refundContent,date);
    }

    /**
     * @Author xiaowu
     * @Description //TODO 获取所有的通用问题信息
     * @Date 9:06 2022/12/29
     * @Param [info, question]
     * @return com.cskaoyan.bean.common.CommonData<com.cskaoyan.bean.vo.WxglMallManagementControllerVo.ListEntityVo>
     **/
    @Override
    public CommonData<ListEntityVo> issueList(BasePageInfo info, String question) {
        //开启分页
        PageHelper.startPage(info.getPage(),info.getLimit());
        MarketIssueExample example = new MarketIssueExample();
        example.setDistinct(true);
        example.setOrderByClause(info.getSort()+ " " + info.getOrder());

        MarketIssueExample.Criteria criteria = example.createCriteria();
        if (question != null && !"".equals(question)){
            criteria.andQuestionLike("%" +question.trim()+ "%");
        }
        if (1==1){
            criteria.andDeletedEqualTo(false);
        }
        List<ListEntityVo> list = orderMapper.selectIssueListByExample(example);
        PageInfo<ListEntityVo> pageInfo = new PageInfo<>(list);
        return CommonData.data(pageInfo);
    }

    /**
     * @Author xiaowu
     * @Description //TODO 新增通用问题
     * @Date 10:50 2022/12/29
     * @Param [map]
     * @return com.cskaoyan.bean.vo.WxglMallManagementControllerVo.IssueCreateVo
     **/
    @Override
    public IssueCreateVo issueCreat(IssueCreateBo bo) {
        String question = bo.getQuestion();
        String answer = bo.getAnswer();
        Date date = new Date();

        MarketIssue marketIssue = new MarketIssue();
        marketIssue.setQuestion(question);
        marketIssue.setAnswer(answer);
        marketIssue.setAddTime(date);
        marketIssue.setUpdateTime(date);

        marketIssueMapper.issueCreat(marketIssue);

        IssueCreateVo issueCreateVo = new IssueCreateVo();
        issueCreateVo.setId(marketIssue.getId());
        issueCreateVo.setQuestion(question);
        issueCreateVo.setAnswer(answer);
        issueCreateVo.setAddTime(date);
        issueCreateVo.setUpdateTime(date);

        return issueCreateVo;
    }
/**
 * @Author xiaowu
 * @Description //TODO 修改通用问题
 * @Date 12:41 2022/12/29
 * @Param [marketIssue]
 * @return com.cskaoyan.bean.marketBean.MarketIssue
 **/

    @Override
    public MarketIssue issueUpdate(MarketIssue marketIssue) {
        Integer id = marketIssue.getId();
        String question = marketIssue.getQuestion();
        String answer = marketIssue.getAnswer();
        Date date = new Date();

        marketIssueMapper.issueUpdate(id,question,answer,date);

        MarketIssue marketIssue1 = new MarketIssue();
        marketIssue1.setId(id);
        marketIssue1.setQuestion(question);
        marketIssue1.setAnswer(answer);
        marketIssue1.setAddTime(marketIssue.getAddTime());
        marketIssue1.setUpdateTime(date);
        marketIssue1.setUpdateTime(date);

        return marketIssue1;
    }

    /**
     * @Author xiaowu
     * @Description //TODO 删除通用问题
     * @Date 12:42 2022/12/29
     * @Param [marketIssue]
     * @return int
     **/
    @Override
    public int issueDelete(MarketIssue marketIssue) {
        int affectedRows = marketIssueMapper.issueDelete(marketIssue.getId());
        if (affectedRows == 1){
            return 200;
        }
        return 10000;
    }

    /**
     * @Author xiaowu
     * @Description //TODO 显示所有关键词
     * @Date 12:42 2022/12/29
     * @Param [keywordListBo]
     * @return com.cskaoyan.bean.common.CommonData<com.cskaoyan.bean.vo.WxglMallManagementControllerVo.KeywordListVo>
     **/
    @Override
    public CommonData<KeywordListVo> keywordList(KeywordListBo bo) {

        //开启分页
        PageHelper.startPage(bo.getPage(),bo.getLimit());
        MarketKeywordExample example = new MarketKeywordExample();
        example.setDistinct(true);
        example.setOrderByClause(bo.getSort()+" "+bo.getOrder());

        MarketKeywordExample.Criteria criteria = example.createCriteria();
        if (bo.getUrl() != null && !"".equals(bo.getUrl())){
            criteria.andUrlLike("%" + bo.getUrl().trim() +"%");
        }
        if (bo.getKeyword() != null && !"".equals(bo.getKeyword())){
            criteria.andKeywordLike("%" + bo.getKeyword().trim() + "%");
        }
        if (1==1){
            criteria.andDeletedEqualTo(false);
        }
        List<KeywordListVo> list = marketKeywordMapper.keywordList(example);
        PageInfo<KeywordListVo> pageInfo = new PageInfo<>(list);

        return CommonData.data(pageInfo);
    }

    @Override
    public MarketKeyword keywordUpdate(MarketKeyword marketKeyword) {
        Integer id = marketKeyword.getId();
        String keyword = marketKeyword.getKeyword();
        String url = marketKeyword.getUrl();
        Boolean isDefault = marketKeyword.getIsDefault();
        Boolean isHot = marketKeyword.getIsHot();
        marketKeyword.setUpdateTime(new Date());

        marketKeywordMapper.keywordUpdate(id,keyword,url,isDefault,isHot);

        return marketKeyword;
    }

    @Override
    public MarketKeyword keywordCreate(MarketKeyword marketKeyword) {
        marketKeyword.setAddTime(new Date());
        marketKeyword.setUpdateTime(new Date());
        marketKeywordMapper.keywordCreate(marketKeyword);
        Integer id = marketKeyword.getId();
        MarketKeyword marketKeyword1 = marketKeywordMapper.selectKeywordById(id);
        Boolean deleted = marketKeyword1.getDeleted();
        Integer sortOrder = marketKeyword1.getSortOrder();

        marketKeyword.setDeleted(deleted);
        marketKeyword1.setSortOrder(sortOrder);

        return marketKeyword;
    }

    @Override
    public void keywordDelete(MarketKeyword marketKeyword) {
        Integer id = marketKeyword.getId();
        marketKeywordMapper.keywordDelete(id);
    }

    @Override
    public PermissionVo rolePermissions(Integer roleId) {
        PermissionVo permissionVo = new PermissionVo();
        List<String> permissions = null;
        if (roleId == 1){
            permissions = marketKeywordMapper.selectAllPermission();
        }else {
            permissions = marketKeywordMapper.selectPermissionByRoleId(roleId);
        }

        permissionVo.setAssignedPermissions(permissions);

        Integer level1Pid = 0;
        List<SystemPermissions> systemPermissions = marketKeywordMapper.selectPermissionByPid(level1Pid);

//        List<SystemPermissions> systemPermissions2 = marketKeywordMapper.selectPermissionByL2Pid(systemPermissions1);
//
//        List<SystemPermissions> systemPermissions3 = marketKeywordMapper.selectPermissionByL3Pid(systemPermissions2);
        for (SystemPermissions systemPermission : systemPermissions) {
            Integer id1 = systemPermission.getNid();
            List<SystemPermissions> systemPermissions2 =marketKeywordMapper.selectPermissionByPid(id1);

            for (SystemPermissions systemPermissions1 : systemPermissions2) {
                Integer id2 = systemPermissions1.getNid();
                List<SystemPermissions> systemPermissions3 =marketKeywordMapper.selectPermissionByPid(id2);
                systemPermissions1.setChildren(systemPermissions3);
            }
            systemPermission.setChildren(systemPermissions2);
        }

        permissionVo.setSystemPermissions(systemPermissions);

        return permissionVo;
    }

    @Override
    public void rolePermissionsPost(PostPermissionBo postPermissionBo) {
        Integer roleId = postPermissionBo.getRoleId();
        List<String> permissions = postPermissionBo.getPermissions();

        marketKeywordMapper.updateRoleIdByPermission(permissions,roleId);
    }


}
